package memcached

import (
	"net"
	"os"
	"bufio"
	"io"
)

const RN = "\r\n"

type Conn struct {
	c      net.Conn
	reader *bufio.Reader
}

func NewConn(c net.Conn) *Conn {
	return &Conn{
		c:      c,
		reader: bufio.NewReader(c),
	}
}

func (c *Conn) ReadLine() (s string, err os.Error) {
	line, isPrefix, err := c.reader.ReadLine()
	if err != nil {
		return
	}
	s += string(line)
	for isPrefix {
		line, isPrefix, err = c.reader.ReadLine()
		if err != nil {
			return
		}
		s += string(line)
	}
	return
}

func (c *Conn) ReadBytes(nbytes uint) (bytes []byte, err os.Error) {
	bytes = make([]byte, nbytes+2)
	_, err = io.ReadFull(c.reader, bytes)
	bytes = bytes[:len(bytes)-2]
	return
}

func (c *Conn) WriteLine(s string) (err os.Error) {
	_, err = io.WriteString(c.c, s + RN)
	return
}

func (c *Conn) WriteBytes(bytes []byte) (err os.Error) {
	_, err = c.c.Write(bytes)
	io.WriteString(c.c, RN)
	return
}

func (c *Conn) Close() (err os.Error) {
	err = c.c.Close()
	return
}